<template>
	<jk-dialog
		v-model="showDialog"
		title="选择-销售订单"
		width="1100px"
		append-to-body
		@on-visible-change="onVisibleChange"
		@on-cancel="onVisibleChange(false)"
		@on-confirm="onConfirmBtn"
	>
		<header ref="box1" class="margin-bottom-4 flex-between-center">
			<div>
				<el-checkbox-group v-model="searchParams.serviceStateList" size="small" @change="onSateChange">
					<el-checkbox-button v-for="item in saleOrderStateList" :key="item.id" :label="item.id">
						<div class="flex-start-center">
							<jk-state-bar :state="item.id" :state-list="saleOrderStateList" :show-text="false"></jk-state-bar>
							<span>{{ item.name }}</span>
						</div>
					</el-checkbox-button>
				</el-checkbox-group>
			</div>
			<div class="flex-end-center">
				<jk-search-input v-model="searchParams.productNameOrCode" class="search-bar-item-size3 item-gap" placeholder="品种编号或名称" @on-enter="onSearchBtn"></jk-search-input>
				<jk-search-input v-model="searchParams.code" class="search-bar-item-size2 item-gap" placeholder="销售单号" @clear="onSearchBtn" @on-enter="onSearchBtn"></jk-search-input>
				<jk-search-button @click="onSearchBtn"></jk-search-button>
			</div>
		</header>

		<jk-table
			ref="jkTable"
			:radio-config="{trigger: 'row'}"
			:loading="tableLoading"
			class="width-100-percent"
			:data="tableData"
			border
			highlight-hover-row
			highlight-current-row
			:height="tableHeight - 80"
			:checkbox-config="{checkMethod: checkboxMethod}"
			@checkbox-change="onCheckBoxChange"
		>
			<vxe-column type="checkbox" width="60" align="center"></vxe-column>
			<vxe-table-column field="saleOrderCode" title="销售单号" :width="144" />
			<vxe-table-column field="saleOrderCustomerName" title="客户" :min-width="180" />
			<vxe-table-column field="productName" title="名称" :min-width="200"> </vxe-table-column>
			<vxe-table-column field="productModels" title="规格型号" :min-width="140"> </vxe-table-column>
			<vxe-table-column field="unitName" title="单位" :width="70" />
			<vxe-table-column field="productQty" title="数量" align="right" :width="90" />
			<vxe-table-column field="awaitAllocatedQty" align="right" title="可下达" :width="80" />
			<vxe-column title="状态" align="left" field="serviceState" :width="86">
				<template slot-scope="scope">
					<jk-state-bar :state="scope.row.serviceState" :state-list="saleOrderStateList"></jk-state-bar>
				</template>
			</vxe-column>
		</jk-table>
		<footer ref="box2" class="flex-end-center margin-top-10">
			<jk-page
				:page-index="searchParams.pageNo"
				:page-sizes="searchParams.pageSizes"
				:page-size="searchParams.pageSize"
				:total="totalCount"
				layout="total, prev, pager, next"
				@on-change="onPageChange"
			/>
		</footer>
	</jk-dialog>
</template>

<script>
    import calDialogHeight from '../../../../../mixins/cal-table-height';
    import { pageConfig, tipsBar } from '../../../../../utils/jk/jk-tool';
    import { productionSaleOrderPage } from '../../../../../api/production/order';
    import { saleOrderStateList } from '../../../../../utils/jk/status-option-list';

    export default {
        mixins: [calDialogHeight],
        props: {
            dialogState: {
                type: Boolean,
                default: false
            },
            checkKeyName: {
                type: String,
                default: 'saleOrderItemId'
            },
            productName: {
                type: String,
                default: ''
            },
            defaultSelectRows: {
                type: Array,
                default() {
                    return [];
                }
            }
        },
        data() {
            return {
                totalCount: 0,
                saleOrderStateList: saleOrderStateList,
                searchParams: {
                    pageNo: 1,
                    pageSize: pageConfig.pageSize,
                    name: null,
                    code: '',
                    productNameOrCode: '',
                    serviceStateList: [0, 1]
                },
                searchBarProcessId: null,
                tableData: [],
                showDialog: false,
                tableLoading: false,
                checkData: []
            };
        },
        methods: {
            validatorCheckData() {
                const arr = [
                    ...JSON.parse(JSON.stringify(this.defaultSelectRows)),
                    ...JSON.parse(JSON.stringify(this.checkData))
                ];
                let ids = arr.map(x => x.productName);
                ids = Array.from(new Set(ids));
                return ids;
            },
            onSateChange() {
                this.$set(this.searchParams, 'pageNo', 1);
                this.getListRequest();
            },
            onCheckBoxChange({ records }) {
                this.checkData = records.filter(x => !x._disabled).map(x => {
                    return x;
                });
                if (this.validatorCheckData().length > 1) {
                    tipsBar(this, 'custom', 'warning', `只能合并相同品种的订单, 当前已选择${this.validatorCheckData().length}个品种!`);
                }
            },
            checkboxMethod(e) {
                return !e.row._disabled;
            },
            onSearchBtn() {
                this.$set(this.searchParams, 'pageNo', 1);
                this.getListRequest();
            },
            onPageChange(e, size) {
                this.$set(this.searchParams, 'pageNo', e);
                this.$set(this.searchParams, 'pageSize', size);
                this.getListRequest();
            },
            onConfirmBtn() {
                if (this.checkData.length) {
                    if (this.validatorCheckData().length === 1) {
                        const arr = this.checkData.filter(x => !x._disabled);
                        this.$emit('on-confirm', arr);
                    } else {
                        tipsBar(this, 'custom', 'warning', `只能合并相同品种的订单, 当前已选择${this.validatorCheckData().length}个品种!`);
                    }
                } else {
                    tipsBar(this, 'checkbox');
                }
            },
            setCheckState(arr) {
                arr.forEach((x) => {
                    x._disabled = false;
                    this.defaultSelectRows.forEach(k => {
                        if (x.id === k[this.checkKeyName]) {
                            x._disabled = true;
                        }
                    });
                });
                this.tableData = arr;
                this.tableData.forEach((x, index) => {
                    if (x._disabled) {
                        this.$refs.jkTable.$refs.xTable.setCheckboxRow([this.tableData[index], this.tableData[index]], true);
                    }
                });
            },
            getListRequest() {
                this.tableLoading = true;
                this.checkData = [];
                return productionSaleOrderPage(this.searchParams).then(res => {
                    this.tableLoading = false;
                    if (res.data.status === 200) {
                        this.totalCount = res.data.count;
                        this.setCheckState(res.data.res || []);
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                }
            },
            async getDependentData() {
                this.tableLoading = true;
                this.$set(this.searchParams, 'productNameOrCode', this.productName || '');
                await this.getListRequest();
                this.tableLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.getDependentData();
                }
            }
        }
    };
</script>
